package com.hspedu.controller;

import com.hspedu.entity.Monster;
import com.hspedu.hspspringmvc.annotation.AutoWired;
import com.hspedu.hspspringmvc.annotation.Controller;
import com.hspedu.hspspringmvc.annotation.RequestMapping;
import com.hspedu.hspspringmvc.annotation.RequestParam;
import com.hspedu.service.MonsterService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class MonsterController {
    @AutoWired
    private MonsterService monsterService;
    @RequestMapping("/monster/list")
    public void listMonsters(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=utf-8");
        try {
            List<Monster> monsters = monsterService.listMonsters();
            StringBuilder content = new StringBuilder("<h1>妖怪列表</h1>");
            content.append("<table width='500px' style='border-collapse: collapse' border='1px'>");
            for (Monster monster : monsters) {
                content.append("<tr><td>" + monster.getId() + "</td><td>" + monster.getName() + "</td><td>" + monster.getSkill()
                        + "</td>");
            }
            content.append("</table>");
            PrintWriter printWriter = response.getWriter();
            printWriter.write(content.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/monster/find")
    public void find(HttpServletRequest request, HttpServletResponse response,String name){
        response.setContentType("text/html;charset=utf-8");
        try {
            List<Monster> monsters = monsterService.findMonstersByName(name);
            StringBuilder content = new StringBuilder("<h1>妖怪列表</h1>");
            content.append("<table width='500px' style='border-collapse: collapse' border='1px'>");
            for (Monster monster : monsters) {
                content.append("<tr><td>" + monster.getId() + "</td><td>" + monster.getName() + "</td><td>" + monster.getSkill()
                        + "</td>");
            }
            content.append("</table>");
            PrintWriter printWriter = response.getWriter();
            printWriter.write(content.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response,@RequestParam("mname") String mname){
        System.out.println("MonsterController.login.mname：" + mname);
        boolean login = monsterService.login(mname);
        if (login){
            return "forward:/login_ok.jsp";
        }else {
            return "forward:/login_error.jsp";
        }
    }
}
